package com.yjr.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServer;
    /**
     * 无需登录
     */
    @ResponseBody
    @GetMapping({"/hello"})
    public String hello(){
        return "hello";
    }

    @GetMapping("/employee")
    public String employees(Model model, @RequestParam(value = "token",required = false) String token, HttpSession session){
        if(!StringUtils.isEmpty(token)){
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://sso.com:8080/userInfo?token=" + token, String.class);
            String body = entity.getBody();
            System.out.println(body);
            session.setAttribute("user",body);

        }
        Object user = session.getAttribute("user");
        if(user==null){
            //没登录
            return  "redirect:"+ssoServer+"?redirect_url=http://clientA.com:8081/employee";
        }
        else {
            ArrayList<String> list = new ArrayList<>();
            list.add("fire");
            list.add("zjl");
            list.add("xjs");
            list.add("nay");
            list.add("mqs");
            session.setAttribute("user", user);
            model.addAttribute("emps", list);

            return "list";
        }



    }

}
